import React, { useState, useEffect, useCallback, useMemo, useRef } from 'react';
import { Modal, Spin, message, Button, Tooltip, Tabs, Table, Typography, Card, List, Space } from 'antd';
import { ZoomInOutlined, ZoomOutOutlined, FullscreenOutlined, UnorderedListOutlined, AppstoreOutlined } from '@ant-design/icons';
import ReactFlow, {
  Background,
  Controls,
  MiniMap,
  useNodesState,
  useEdgesState,
  Panel,
  MarkerType,
  Handle,
  Position,
  useReactFlow
} from 'reactflow';
import 'reactflow/dist/style.css';
import axios from 'axios';
import { API_BASE_URL } from '../config';

const { Title, Text } = Typography;
// Remove the TabPane destructuring since we'll use items prop
// const { TabPane } = Tabs;

// 自定义节点样式
const customNodeStyles = {
  start: {
    background: '#d4f7d4',
    border: '1px solid #6bcb77',
    color: '#2c6e49',
    borderRadius: '50%',
    width: 60,
    height: 60,
    display: 'flex',
    justifyContent: 'center',
    alignItems: 'center',
    fontWeight: 'bold'
  },
  end: {
    background: '#ffd8d6',
    border: '1px solid #ff6b6b',
    color: '#d62828',
    borderRadius: '50%',
    width: 60,
    height: 60,
    display: 'flex',
    justifyContent: 'center',
    alignItems: 'center',
    fontWeight: 'bold'
  },
  operation: {
    background: '#e1f1ff',
    border: '1px solid #5fa8d3',
    color: '#1766a3',
    borderRadius: 4,
    padding: '10px',
    width: 150,
    boxShadow: '0 2px 4px rgba(0,0,0,0.1)'
  },
  step: {
    background: '#f0f0ff',
    border: '1px solid #a0a0e1',
    color: '#0000cc',
    borderRadius: 4,
    padding: '8px',
    width: 130,
    boxShadow: '0 2px 4px rgba(0,0,0,0.1)'
  }
};

// 自定义节点组件
const CustomNode = ({ data }) => {
  const nodeStyle = customNodeStyles[data.type] || customNodeStyles.operation;
  
  return (
    <div 
      style={nodeStyle}
      className="custom-node"
      onClick={() => data.onClick && data.onClick(data)}
    >
      {/* 源连接点 */}
      <Handle 
        type="source" 
        position={Position.Bottom} 
        style={{ 
          background: '#555',
          width: 8,
          height: 8
        }} 
        id={`${data.id}-source`}
      />
      
      <div style={{ fontWeight: data.type === 'operation' ? 'bold' : 'normal' }}>
        {data.label}
      </div>
      {data.description && (
        <div style={{ 
          fontSize: '12px', 
          marginTop: '4px',
          color: 'rgba(0,0,0,0.65)',
          textOverflow: 'ellipsis',
          overflow: 'hidden',
          whiteSpace: 'nowrap'
        }}>
          {data.description.length > 20 ? data.description.substring(0, 20) + '...' : data.description}
        </div>
      )}
      
      {/* 目标连接点 */}
      <Handle 
        type="target" 
        position={Position.Top} 
        style={{ 
          background: '#555',
          width: 8,
          height: 8
        }} 
        id={`${data.id}-target`}
      />
    </div>
  );
};

// 节点类型映射 - 使用useMemo来避免重新创建对象
const ProcessFlowChart = ({ templateId, routeId, isOpen, onClose }) => {
  const [nodes, setNodes, onNodesChange] = useNodesState([]);
  const [edges, setEdges, onEdgesChange] = useEdgesState([]);
  const [loading, setLoading] = useState(false);
  const [selectedNode, setSelectedNode] = useState(null);
  const [nodeDetailVisible, setNodeDetailVisible] = useState(false);
  const [operationDetail, setOperationDetail] = useState(null);
  const [operationSteps, setOperationSteps] = useState([]);
  const [loadingDetail, setLoadingDetail] = useState(false);
  const [activeTabKey, setActiveTabKey] = useState('basic');
  
  // 创建一个ref用于ReactFlow实例
  const reactFlowWrapper = useRef(null);
  const [reactFlowInstance, setReactFlowInstance] = useState(null);

  const [isMobile, setIsMobile] = useState(false);
  const [viewMode, setViewMode] = useState('table'); // 'table' 或 'card'
  
  // 使用useMemo避免重新创建节点类型对象
  const nodeTypes = useMemo(() => ({
    customNode: CustomNode,
  }), []);

  // 检测是否为移动端
  useEffect(() => {
    const checkIsMobile = () => {
      setIsMobile(window.innerWidth <= 768);
    };
    
    checkIsMobile();
    window.addEventListener('resize', checkIsMobile);
    
    return () => {
      window.removeEventListener('resize', checkIsMobile);
    };
  }, []);

  // 获取流程图数据
  useEffect(() => {
    if (isOpen && (templateId || routeId)) {
      fetchFlowChartData();
    }
  }, [isOpen, templateId, routeId]);

  // 处理节点点击事件
  const handleNodeClick = (node) => {
    setSelectedNode(node);
    setNodeDetailVisible(true);
    
    // 如果是工序节点，获取详细信息和工步列表
    if (node.type === 'operation' && node.details && node.details.id) {
      const operationId = node.details.id.replace('op', ''); // 从节点ID提取工序ID (例如：op1 -> 1)
      fetchOperationDetail(operationId);
      fetchOperationSteps(operationId);
    }
  };

  // 获取工序详情
  const fetchOperationDetail = async (operationId) => {
    setLoadingDetail(true);
    try {
      // 根据提供的ID类型决定调用哪个API
      let apiUrl = routeId 
        ? `${API_BASE_URL}/api/product_process_operation/${operationId}` 
        : `${API_BASE_URL}/api/process_template_operation/${operationId}`;
        
      const response = await axios.get(apiUrl);
      
      if (response.data && response.data.code === 200) {
        console.log('工序详情数据:', response.data.data);
        setOperationDetail(response.data.data);
      } else {
        message.error('获取工序详情失败: ' + (response.data.message || '未知错误'));
      }
    } catch (error) {
      console.error('获取工序详情错误:', error);
      message.error('获取工序详情失败: ' + (error.message || '网络错误'));
    } finally {
      setLoadingDetail(false);
    }
  };
  
  // 获取工序下的工步列表
  const fetchOperationSteps = async (operationId) => {
    try {
      // 根据提供的ID类型决定调用哪个API
      let apiUrl = routeId 
        ? `${API_BASE_URL}/api/product_process_step` 
        : `${API_BASE_URL}/api/process_template_step`;
        
      const response = await axios.get(apiUrl, {
        params: {
          operation_id: operationId,
          page: 1,
          size: 50
        }
      });
      
      if (response.data && response.data.code === 200) {
        console.log('工步列表数据:', response.data.data);
        setOperationSteps(response.data.data.items || []);
      } else {
        message.error('获取工步列表失败: ' + (response.data.message || '未知错误'));
      }
    } catch (error) {
      console.error('获取工步列表错误:', error);
      message.error('获取工步列表失败: ' + (error.message || '网络错误'));
    }
  };

  // 关闭节点详情弹窗
  const handleCloseNodeDetail = () => {
    setNodeDetailVisible(false);
    setOperationDetail(null);
    setOperationSteps([]);
    setActiveTabKey('basic');
  };

  // 切换Tab
  const handleTabChange = (activeKey) => {
    setActiveTabKey(activeKey);
  };

  // 转换流程图数据为ReactFlow格式
  const convertFlowChartData = (flowChart) => {
    if (!flowChart || !flowChart.nodes || !flowChart.edges) {
      return { nodes: [], edges: [] };
    }

    // 检查数据结构
    console.log('原始流程图数据:', flowChart);
    
    try {
      // 确保nodes和edges是数组
      const nodeArray = Array.isArray(flowChart.nodes) ? flowChart.nodes : [];
      const edgeArray = Array.isArray(flowChart.edges) ? flowChart.edges : [];
      
      if (nodeArray.length === 0) {
        console.warn('流程图没有节点数据');
        return { nodes: [], edges: [] };
      }
      
      // 转换节点数据
      const nodes = nodeArray.map(node => {
        // 提取节点类型，默认为"operation"
        const nodeType = node.type || 'operation';
        
        // 设置节点样式和属性
        return {
          id: node.id,
          type: 'customNode',
          data: {
            label: node.name,
            description: node.description,
            type: nodeType,
            onClick: handleNodeClick,
            // 添加原始节点详情，便于后续查询
            details: {
              id: node.id,
              name: node.name,
              type: nodeType,
              description: node.description
            }
          },
          position: { x: 0, y: 0 }, // 位置将在后面的步骤中计算
        };
      });
      
      // 转换边数据
      const edges = edgeArray.map((edge, index) => {
        return {
          id: `edge-${index}`,
          source: edge.source,
          target: edge.target,
          type: 'smoothstep',
          animated: false,
          style: { stroke: '#555' },
          markerEnd: {
            type: MarkerType.ArrowClosed,
          },
        };
      });
      
      return { nodes, edges };
    } catch (error) {
      console.error('转换流程图数据错误:', error);
      message.error('解析流程图数据失败');
      return { nodes: [], edges: [] };
    }
  };

  // 获取流程图数据
  const fetchFlowChartData = async () => {
    setLoading(true);
    try {
      let response;
      let flowChartData;

      // 根据提供的ID决定调用哪个API
      if (routeId) {
        // 如果有routeId，使用产品工艺流程API
        response = await axios.get(`${API_BASE_URL}/api/product_process_route/${routeId}`);
        
        if (response.data && response.data.code === 200) {
          console.log('工艺流程数据:', response.data.data);
          // 从响应中获取flow_chart字段
          const flowChartString = response.data.data.flow_chart;
          // 将JSON字符串解析为对象
          if (flowChartString) {
            try {
              flowChartData = JSON.parse(flowChartString);
            } catch (parseError) {
              console.error('解析流程图数据错误:', parseError);
              message.error('流程图数据格式错误');
              setLoading(false);
              return;
            }
          } else {
            message.warning('流程图数据不存在');
            setLoading(false);
            return;
          }
        } else {
          message.error('获取工艺流程数据失败: ' + (response.data.message || '未知错误'));
          setLoading(false);
          return;
        }
      } else if (templateId) {
        // 如果有templateId，使用工艺模板API
        response = await axios.get(`${API_BASE_URL}/api/process_template_info/${templateId}`);
        
        if (response.data && response.data.code === 200) {
          console.log('模板流程图数据:', response.data.data);
          // 从响应中获取flow_chart字段
          const flowChartString = response.data.data.flow_chart;
          // 将JSON字符串解析为对象
          if (flowChartString) {
            try {
              flowChartData = JSON.parse(flowChartString);
            } catch (parseError) {
              console.error('解析流程图数据错误:', parseError);
              message.error('流程图数据格式错误');
              setLoading(false);
              return;
            }
          } else {
            message.warning('流程图数据不存在');
            setLoading(false);
            return;
          }
        } else {
          message.error('获取模板流程图数据失败: ' + (response.data.message || '未知错误'));
          setLoading(false);
          return;
        }
      } else {
        message.error('未提供模板ID或工艺路线ID');
        setLoading(false);
        return;
      }

      // 转换流程图数据并更新状态
      if (flowChartData) {
        // 转换流程图数据为节点和边
        const { nodes, edges } = convertFlowChartData(flowChartData);
        
        // 如果有节点，计算节点位置
        if (nodes.length > 0) {
          // 计算节点层级和位置
          const nodePositions = calculateNodePositions(nodes, edges);
          
          // 应用节点位置
          const positionedNodes = nodes.map(node => ({
            ...node,
            position: nodePositions[node.id] || { x: 0, y: 0 }
          }));
          
          // 设置节点和边
          setNodes(positionedNodes);
          setEdges(edges);
        } else {
          setNodes([]);
          setEdges([]);
          message.warning('没有检测到流程图节点数据');
        }
      }
    } catch (error) {
      console.error('获取流程图数据错误:', error);
      message.error('获取流程图数据失败: ' + (error.message || '网络错误'));
    } finally {
      setLoading(false);
    }
  };

  // 计算节点位置
  const calculateNodePositions = (nodes, edges) => {
    // 创建节点ID到节点的映射
    const nodeMap = {};
    nodes.forEach(node => {
      nodeMap[node.id] = node;
    });
    
    // 创建连接关系映射
    const connections = {};
    edges.forEach(edge => {
      if (!connections[edge.source]) {
        connections[edge.source] = [];
      }
      connections[edge.source].push(edge.target);
      
      // 创建入边映射，用于确定前驱节点
      if (!connections[edge.target]) {
        connections[edge.target] = [];
      }
    });
    
    // 查找开始节点（没有入边的节点）
    const allNodes = nodes.map(node => node.id);
    const targetNodes = edges.map(edge => edge.target);
    const startNodes = allNodes.filter(nodeId => !targetNodes.includes(nodeId));
    
    // 如果没有找到开始节点，使用第一个节点作为开始
    const rootNodes = startNodes.length > 0 ? startNodes : (allNodes.length > 0 ? [allNodes[0]] : []);
    
    // 使用BFS分配节点到层级
    const levels = {};
    let currentLevel = 0;
    let currentNodes = [...rootNodes];
    let visited = new Set();
    
    while (currentNodes.length > 0 && currentLevel < 20) { // 防止无限循环
      levels[currentLevel] = [...currentNodes];
      const nextLevelNodes = [];
      
      currentNodes.forEach(nodeId => {
        visited.add(nodeId);
        const outNodes = connections[nodeId] || [];
        
        outNodes.forEach(targetId => {
          if (!Object.values(levels).flat().includes(targetId)) {
            nextLevelNodes.push(targetId);
          }
        });
      });
      
      currentLevel++;
      currentNodes = [...new Set(nextLevelNodes)];
    }
    
    // 检查是否有未访问的节点，放入最后一层
    const unvisitedNodes = allNodes.filter(nodeId => !visited.has(nodeId));
    if (unvisitedNodes.length > 0) {
      levels[currentLevel] = unvisitedNodes;
    }
    
    // 计算每个节点的坐标
    const nodePositions = {};
    const horizontalSpacing = 250; // 增加水平间距
    const verticalSpacing = 150;  // 增加垂直间距
    
    Object.keys(levels).forEach((level, levelIndex) => {
      const levelNodes = levels[level];
      const levelWidth = levelNodes.length * horizontalSpacing;
      
      levelNodes.forEach((nodeId, nodeIndex) => {
        // 居中对齐当前层的节点
        const xOffset = levelNodes.length > 1 
          ? -levelWidth / 2 + horizontalSpacing / 2 
          : 0;
        
        nodePositions[nodeId] = {
          x: nodeIndex * horizontalSpacing + xOffset,
          y: levelIndex * verticalSpacing
        };
      });
    });
    
    return nodePositions;
  };

  // 格式化日期
  const formatDate = (dateString) => {
    if (!dateString) return '-';
    try {
      const date = new Date(dateString);
      if (!isNaN(date.getTime())) {
        return date.toLocaleString('zh-CN', {
          year: 'numeric',
          month: '2-digit',
          day: '2-digit',
          hour: '2-digit',
          minute: '2-digit',
          second: '2-digit',
          hour12: false
        }).replace(/\//g, '-');
      }
      return dateString;
    } catch (error) {
      console.error('日期格式化错误:', error);
      return dateString || '-';
    }
  };

  // 渲染节点详情
  const renderNodeDetail = () => {
    // 如果没有选择节点或弹窗未显示，则返回null
    if (!selectedNode || !nodeDetailVisible) return null;
    
    // 检查所选节点是否为工序类型
    const isOperation = selectedNode.type === 'operation';
    
    // Tab项配置
    const tabItems = [
      {
        key: 'basic',
        label: '基本信息',
        children: renderOperationBasicInfo()
      },
      {
        key: 'steps',
        label: '工步列表',
        children: renderOperationSteps(),
        tabBarExtraContent: isMobile ? (
          <Space>
            <Button
              type={viewMode === 'table' ? 'primary' : 'text'}
              icon={<UnorderedListOutlined />}
              size="small"
              onClick={() => setViewMode('table')}
            />
            <Button
              type={viewMode === 'card' ? 'primary' : 'text'}
              icon={<AppstoreOutlined />}
              size="small"
              onClick={() => setViewMode('card')}
            />
          </Space>
        ) : null
      }
    ];
    
    // 自定义样式
    const detailStyles = `
      .detail-content {
        margin-bottom: 16px;
      }
      .detail-header {
        border-bottom: 1px solid #f0f0f0;
        padding-bottom: 8px;
        margin-bottom: 12px;
      }
      .detail-title {
        font-weight: bold;
        font-size: 16px;
        color: #222;
      }
      .detail-item {
        display: flex;
        margin-bottom: 8px;
        align-items: baseline;
        padding: 8px 0;
        border-bottom: 1px solid #f0f0f0;
      }
      .detail-label {
        width: 120px;
        color: #666;
        flex-shrink: 0;
        font-weight: bold;
        padding-right: 16px;
        font-size: 14px;
      }
      .detail-value {
        flex: 1;
        word-break: break-word;
        font-size: 14px;
        color: #333;
      }
    `;
    
    // 移动端非工序节点样式
    const mobileNodeDetailItemStyle = {
      display: 'flex',
      flexDirection: 'row',
      alignItems: 'center',
      padding: '8px 0',
      borderBottom: '1px solid #f0f0f0',
    };
    
    const mobileNodeDetailLabelStyle = {
      width: '30%',
      fontSize: '14px',
      color: '#666',
      paddingRight: '8px',
      flexShrink: 0,
    };
    
    const mobileNodeDetailValueStyle = {
      flex: 1,
      fontSize: '14px',
      wordBreak: 'break-word',
    };
    
    // 电脑端非工序节点样式
    const desktopNodeDetailItemStyle = {
      display: 'flex',
      flexDirection: 'row',
      alignItems: 'baseline',
      padding: '8px 0',
      borderBottom: '1px solid #f0f0f0',
      marginBottom: '4px',
    };
    
    const desktopNodeDetailLabelStyle = {
      width: '120px',
      fontSize: '14px',
      color: '#666',
      paddingRight: '16px',
      flexShrink: 0,
      fontWeight: 'bold',
    };
    
    const desktopNodeDetailValueStyle = {
      flex: 1,
      fontSize: '14px',
      wordBreak: 'break-word',
      color: '#333',
    };
    
    return (
      <Modal
        title={`${selectedNode.label} ${isOperation ? '工序详情' : '节点详情'}`}
        open={nodeDetailVisible}
        onCancel={handleCloseNodeDetail}
        footer={null}
        destroyOnHidden={true}
        maskClosable={false}
        width={isMobile ? '100%' : 800}
        styles={{ 
          body: { padding: '10px 24px' },
          mask: { backgroundColor: 'rgba(0,0,0,0.65)' },
          header: { padding: isMobile ? '12px 16px' : '16px 24px' }
        }}
      >
        <style dangerouslySetInnerHTML={{ __html: detailStyles }} />
        <Spin spinning={loadingDetail && isOperation}>
          {isOperation ? (
            <Tabs activeKey={activeTabKey} onChange={handleTabChange} items={tabItems} />
          ) : (
            <div style={{ padding: '10px 0' }}>
              <div className="detail-content">
                <div className="detail-header">
                  <div className="detail-title" style={{ 
                    fontSize: isMobile ? '16px' : '18px',
                    fontWeight: 'bold',
                    borderBottom: '1px solid #e8e8e8',
                    paddingBottom: '8px'
                  }}>{selectedNode.type === 'start' ? '开始节点' : selectedNode.type === 'end' ? '结束节点' : '节点'} 详情</div>
                </div>
                
                <div style={isMobile ? mobileNodeDetailItemStyle : desktopNodeDetailItemStyle}>
                  <div style={isMobile ? mobileNodeDetailLabelStyle : desktopNodeDetailLabelStyle}>名称:</div>
                  <div style={isMobile ? mobileNodeDetailValueStyle : desktopNodeDetailValueStyle}>{selectedNode.label}</div>
                </div>
                
                <div style={isMobile ? mobileNodeDetailItemStyle : desktopNodeDetailItemStyle}>
                  <div style={isMobile ? mobileNodeDetailLabelStyle : desktopNodeDetailLabelStyle}>类型:</div>
                  <div style={isMobile ? mobileNodeDetailValueStyle : desktopNodeDetailValueStyle}>
                    {selectedNode.type === 'start' ? '开始节点' : 
                    selectedNode.type === 'end' ? '结束节点' : 
                    selectedNode.type === 'operation' ? '工序' : '工步'}
                  </div>
                </div>
                
                {selectedNode.description && (
                  <div style={isMobile ? mobileNodeDetailItemStyle : desktopNodeDetailItemStyle}>
                    <div style={isMobile ? mobileNodeDetailLabelStyle : desktopNodeDetailLabelStyle}>描述:</div>
                    <div style={isMobile ? mobileNodeDetailValueStyle : desktopNodeDetailValueStyle}>{selectedNode.description}</div>
                  </div>
                )}
              </div>
            </div>
          )}
        </Spin>
      </Modal>
    );
  };
  
  // 渲染工序基本信息
  const renderOperationBasicInfo = () => {
    // 如果没有获取到工序详情数据，显示占位内容
    if (!operationDetail) {
      return (
        <div style={{ padding: '20px 0', textAlign: 'center' }}>
          {loadingDetail ? '加载中...' : '暂无详细信息'}
        </div>
      );
    }
    
    // 移动端和桌面端不同的样式
    const detailItemStyle = isMobile ? {
      display: 'flex',
      flexDirection: 'row',
      alignItems: 'center',
      padding: '8px 0',
      borderBottom: '1px solid #f0f0f0',
    } : {
      display: 'flex',
      flexDirection: 'row',
      alignItems: 'baseline',
      padding: '8px 0',
      borderBottom: '1px solid #f0f0f0',
      marginBottom: '4px',
    };

    const detailLabelStyle = isMobile ? {
      width: '35%',
      fontSize: '14px',
      color: '#666',
      paddingRight: '8px',
      flexShrink: 0,
    } : {
      width: '120px',
      fontSize: '14px',
      color: '#666',
      paddingRight: '16px',
      flexShrink: 0,
      fontWeight: 'bold',
    };

    const detailValueStyle = isMobile ? {
      flex: 1,
      fontSize: '14px',
      wordBreak: 'break-word',
    } : {
      flex: 1,
      fontSize: '14px',
      color: '#333',
      wordBreak: 'break-word',
    };
    
    return (
      <div className="detail-content" style={{ padding: isMobile ? '8px' : '16px' }}>
        <div className="detail-header" style={{ marginBottom: isMobile ? '12px' : '16px' }}>
          <div className="detail-title" style={{ 
            fontSize: isMobile ? '16px' : '18px',
            fontWeight: 'bold',
            borderBottom: '1px solid #e8e8e8',
            paddingBottom: '8px'
          }}>工序信息</div>
        </div>
        
        <div style={detailItemStyle}>
          <div style={detailLabelStyle}>编码:</div>
          <div style={detailValueStyle}>{operationDetail.code || '-'}</div>
        </div>
        
        <div style={detailItemStyle}>
          <div style={detailLabelStyle}>名称:</div>
          <div style={detailValueStyle}>{operationDetail.name || '-'}</div>
        </div>
        
        <div style={detailItemStyle}>
          <div style={detailLabelStyle}>顺序:</div>
          <div style={detailValueStyle}>{operationDetail.sequence || '-'}</div>
        </div>
        
        <div style={detailItemStyle}>
          <div style={detailLabelStyle}>工序类型:</div>
          <div style={detailValueStyle}>{operationDetail.operation_type || '-'}</div>
        </div>
        
        <div style={detailItemStyle}>
          <div style={detailLabelStyle}>标准执行时间:</div>
          <div style={detailValueStyle}>{operationDetail.standard_time ? `${operationDetail.standard_time} 分钟` : '-'}</div>
        </div>
        
        <div style={detailItemStyle}>
          <div style={detailLabelStyle}>责任部门:</div>
          <div style={detailValueStyle}>{operationDetail.department || '-'}</div>
        </div>
        
        {operationDetail.description && (
          <div style={detailItemStyle}>
            <div style={detailLabelStyle}>描述:</div>
            <div style={detailValueStyle}>{operationDetail.description}</div>
          </div>
        )}
        
        {operationDetail.required_resources && (
          <div style={detailItemStyle}>
            <div style={detailLabelStyle}>所需资源:</div>
            <div style={detailValueStyle}>{operationDetail.required_resources}</div>
          </div>
        )}
        
        {operationDetail.quality_standards && (
          <div style={detailItemStyle}>
            <div style={detailLabelStyle}>质量标准:</div>
            <div style={detailValueStyle}>{operationDetail.quality_standards}</div>
          </div>
        )}
        
        <div style={detailItemStyle}>
          <div style={detailLabelStyle}>创建时间:</div>
          <div style={detailValueStyle}>{operationDetail.create_time ? formatDate(operationDetail.create_time) : '-'}</div>
        </div>
        
        <div style={detailItemStyle}>
          <div style={detailLabelStyle}>更新时间:</div>
          <div style={detailValueStyle}>{operationDetail.update_time ? formatDate(operationDetail.update_time) : '-'}</div>
        </div>
      </div>
    );
  };
  
  // 渲染工步列表
  const renderOperationSteps = () => {
    // 如果是移动端且选择卡片视图
    if (isMobile && viewMode === 'card') {
      return (
        <List
          grid={{ gutter: 16, column: 1 }}
          dataSource={operationSteps}
          renderItem={(item) => (
            <List.Item key={item.id}>
              <Card 
                size="small"
                title={
                  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                    <span>{item.name}</span>
                    <span style={{ 
                      fontSize: '12px', 
                      color: '#999', 
                      fontWeight: 'normal',
                      marginLeft: '8px'
                    }}>
                      {item.code}
                    </span>
                  </div>
                }
              >
                <div style={{ marginBottom: 8 }}>
                  <div style={{ fontWeight: 'bold', fontSize: '13px', marginBottom: 4 }}>序号：</div>
                  <div>{item.sequence || '-'}</div>
                </div>
                <div style={{ marginBottom: 8 }}>
                  <div style={{ fontWeight: 'bold', fontSize: '13px', marginBottom: 4 }}>标准时间：</div>
                  <div>{item.standard_time ? `${item.standard_time} 分钟` : '-'}</div>
                </div>
                {item.description && (
                  <div>
                    <div style={{ fontWeight: 'bold', fontSize: '13px', marginBottom: 4 }}>描述：</div>
                    <div>{item.description}</div>
                  </div>
                )}
              </Card>
            </List.Item>
          )}
          style={{ maxHeight: '400px', overflow: 'auto' }}
        />
      );
    }
    
    // 定义表格列 - 根据是否为移动端调整列布局
    const columns = isMobile 
      ? [
          {
            title: '序号',
            dataIndex: 'sequence',
            key: 'sequence',
            width: 60,
            render: (text) => text || '-'
          },
          {
            title: '工步编码',
            dataIndex: 'code',
            key: 'code',
            width: 100,
          },
          {
            title: '工步名称',
            dataIndex: 'name',
            key: 'name',
            ellipsis: true,
          }
        ]
      : [
          {
            title: '序号',
            dataIndex: 'sequence',
            key: 'sequence',
            width: 80,
            render: (text) => text || '-'
          },
          {
            title: '工步编码',
            dataIndex: 'code',
            key: 'code',
            width: 120,
          },
          {
            title: '工步名称',
            dataIndex: 'name',
            key: 'name',
          },
          {
            title: '工步描述',
            dataIndex: 'description',
            key: 'description',
            ellipsis: true,
          },
          {
            title: '标准时间(分钟)',
            dataIndex: 'standard_time',
            key: 'standard_time',
            width: 140,
            render: (text) => text || '-'
          }
        ];
    
    // 为移动端添加展开行功能
    const expandable = isMobile ? {
      expandedRowRender: (record) => (
        <div style={{ padding: '8px 0' }}>
          <div style={{ marginBottom: 8 }}>
            <span style={{ fontWeight: 'bold' }}>标准时间：</span>
            <span>{record.standard_time ? `${record.standard_time} 分钟` : '-'}</span>
          </div>
          {record.description && (
            <div>
              <span style={{ fontWeight: 'bold' }}>描述：</span>
              <span>{record.description}</span>
            </div>
          )}
        </div>
      ),
      rowExpandable: (record) => record.description || record.standard_time,
    } : undefined;
    
    return (
      <div style={{ marginTop: 16 }}>
        {operationSteps.length > 0 ? (
          <Table 
            columns={columns}
            dataSource={operationSteps.map(item => ({ ...item, key: item.id }))}
            size={isMobile ? "small" : "middle"}
            pagination={false}
            scroll={{ y: isMobile ? 250 : 300 }}
            expandable={expandable}
          />
        ) : (
          <div style={{ textAlign: 'center', padding: '20px 0' }}>
            暂无工步数据
          </div>
        )}
      </div>
    );
  };

  // 使用useMemo缓存defaultEdgeOptions
  const defaultEdgeOptions = useMemo(() => ({
    type: 'smoothstep',
    style: { stroke: '#888', strokeWidth: 1.5 },
    markerEnd: { type: MarkerType.ArrowClosed }
  }), []);

  // 处理缩放控制
  const handleZoomIn = () => {
    if (reactFlowInstance) {
      reactFlowInstance.zoomIn();
    }
  };

  const handleZoomOut = () => {
    if (reactFlowInstance) {
      reactFlowInstance.zoomOut();
    }
  };

  const handleFitView = () => {
    if (reactFlowInstance) {
      reactFlowInstance.fitView({ padding: 0.1 });
    }
  };

  // onInit回调，获取ReactFlow实例
  const onInit = useCallback((instance) => {
    setReactFlowInstance(instance);
  }, []);

  return (
    <Modal
      title="工艺流程图"
      open={isOpen}
      onCancel={onClose}
      footer={null}
      width={isMobile ? '100%' : 1000}
      styles={{ 
        body: { height: isMobile ? '70vh' : '600px', padding: '0' },
        mask: { backgroundColor: 'rgba(0,0,0,0.65)' }
      }}
      destroyOnHidden={true}
      centered={true}
    >
      <div style={{ width: '100%', height: '100%', position: 'relative' }} ref={reactFlowWrapper}>
        {loading ? (
          <div style={{ 
            display: 'flex', 
            justifyContent: 'center', 
            alignItems: 'center', 
            height: '100%' 
          }}>
            <div className="ant-spin-nested-loading" style={{ width: '100%', textAlign: 'center' }}>
              <div className="ant-spin-container">
                <Spin size="large" tip="加载中..." />
              </div>
            </div>
          </div>
        ) : (
          <ReactFlow
            nodes={nodes}
            edges={edges}
            onNodesChange={onNodesChange}
            onEdgesChange={onEdgesChange}
            nodeTypes={nodeTypes}
            fitView
            fitViewOptions={{ padding: 0.2 }}
            minZoom={0.5}
            maxZoom={2}
            attributionPosition="bottom-right"
            defaultEdgeOptions={defaultEdgeOptions}
            onInit={onInit}
            connectionLineStyle={{ stroke: '#888', strokeWidth: 1.5 }}
            snapToGrid={true}
            snapGrid={[15, 15]}
          >
            <Background color="#f8f8f8" gap={16} />
            <Controls position="bottom-right" />
            <MiniMap
              nodeStrokeColor={(n) => {
                if (n.data.type === 'start') return '#6bcb77';
                if (n.data.type === 'end') return '#ff6b6b';
                return '#5fa8d3';
              }}
              nodeColor={(n) => {
                if (n.data.type === 'start') return '#d4f7d4';
                if (n.data.type === 'end') return '#ffd8d6';
                return '#e1f1ff';
              }}
              style={{ backgroundColor: '#f5f5f5' }}
            />
            <Panel position="top-right">
              <div style={{ 
                display: 'flex', 
                flexDirection: 'column', 
                gap: '8px',
                background: 'white',
                padding: '8px',
                borderRadius: '4px',
                boxShadow: '0 2px 4px rgba(0,0,0,0.1)'
              }}>
                <Tooltip title="放大">
                  <Button 
                    icon={<ZoomInOutlined />} 
                    onClick={handleZoomIn}
                  />
                </Tooltip>
                <Tooltip title="缩小">
                  <Button 
                    icon={<ZoomOutOutlined />} 
                    onClick={handleZoomOut}
                  />
                </Tooltip>
                <Tooltip title="适应屏幕">
                  <Button 
                    icon={<FullscreenOutlined />} 
                    onClick={handleFitView}
                  />
                </Tooltip>
              </div>
            </Panel>
          </ReactFlow>
        )}
      </div>
      
      {renderNodeDetail()}
    </Modal>
  );
};

export default ProcessFlowChart; 